#!/usr/bin/env bash
#
# Tape DSP uninstaller (Linux app executable). GUI when zenity/kdialog is available.
# Bundled as "Uninstall Tape DSP/" app folder in the release zip.
set -euo pipefail

HERE="$(cd "$(dirname "$0")" && pwd)"
CORE="$HERE/uninstall-core.sh"
if [ ! -f "$CORE" ]; then
  echo "Uninstaller error: a required file is missing from this app bundle." >&2
  exit 1
fi
# shellcheck source=uninstall-core.sh
source "$CORE"

if [ "${1:-}" = "--system-only" ]; then
  tape_dsp_remove_system_plugins
  exit 0
fi

tape_dsp_ui_message() {
  local title="$1" text="$2" icon="${3:-info}"
  if command -v zenity >/dev/null 2>&1; then
    zenity --"$icon" --title="$title" --text="$text" --width=420 2>/dev/null || true
    return 0
  fi
  if command -v kdialog >/dev/null 2>&1; then
    case "$icon" in
      error) kdialog --title "$title" --error "$text" 2>/dev/null || true ;;
      warning) kdialog --title "$title" --sorry "$text" 2>/dev/null || true ;;
      *) kdialog --title "$title" --msgbox "$text" 0 0 2>/dev/null || true ;;
    esac
    return 0
  fi
  printf '%s\n\n%s\n' "$title" "$text"
}

tape_dsp_ui_confirm() {
  local title="$1" text="$2"
  if command -v zenity >/dev/null 2>&1; then
    zenity --question --title="$title" --text="$text" --width=420 2>/dev/null
    return $?
  fi
  if command -v kdialog >/dev/null 2>&1; then
    kdialog --title "$title" --yesno "$text" 0 0 2>/dev/null
    return $?
  fi
  printf '%s\n\n%s\n\nContinue? [y/N] ' "$title" "$text"
  read -r ans
  case "$ans" in
    y|Y|yes|YES) return 0 ;;
    *) return 1 ;;
  esac
}

if [ "${TAPE_UNINSTALL_YES:-}" = "1" ]; then
  :
elif ! tape_dsp_ui_confirm "Uninstall Tape DSP" \
  "This removes Tape DSP Machine, Echo and Compressor (VST3 + LV2) from this computer.

You may be asked for your administrator password to remove system-wide plug-ins."; then
  exit 0
fi

tape_dsp_remove_user_plugins

if [ "$(id -u)" = 0 ]; then
  tape_dsp_remove_system_plugins
elif command -v pkexec >/dev/null 2>&1; then
  pkexec "$HERE/uninstall" --system-only || {
    tape_dsp_ui_message "Uninstall cancelled" "System-wide plug-ins were not removed." warning
    exit 1
  }
elif command -v sudo >/dev/null 2>&1; then
  sudo "$HERE/uninstall" --system-only || {
    tape_dsp_ui_message "Uninstall cancelled" "System-wide plug-ins were not removed." warning
    exit 1
  }
fi

tape_dsp_forget_deb_package
tape_dsp_remove_app_folder

tape_dsp_ui_message "Tape DSP removed" "The plug-ins have been removed from this computer."
